package de.ifi.lmu.snitzelhunt.view;

import java.util.ArrayList;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import de.ifi.lmu.snitzelhunt.R;
import de.ifi.lmu.snitzelhunt.basics.Task;
import de.ifi.lmu.snitzelhunt.util.GSonUtility;

public class Activity_GPS extends ActionBarActivity implements
		GooglePlayServicesClient.ConnectionCallbacks,
		GooglePlayServicesClient.OnConnectionFailedListener {
	private GoogleMap gm;
	private String readFromIntent;
	private ArrayList<Task> tempTaskList;

	private Marker selectedMark;

	private LatLng userPos;
	private LocationClient loMan;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gps);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}

		Intent intent = getIntent();
		readFromIntent = intent.getStringExtra("TaskInfo");
		tempTaskList = GSonUtility.deserializeTaskList(readFromIntent);

		loMan = new LocationClient(this, this, this);
		Log.i("LocationClient", "instantiated");
	}

	private void setUpMap() {
		if (gm == null) {
			gm = ((SupportMapFragment) getSupportFragmentManager()
					.findFragmentById(R.id.fragment_selectTaskPositionMap))
					.getMap();
			if (gm != null) {
				configureMap();
			}
		} else {

		}
	}

	private void configureMap() {
		gm.setMyLocationEnabled(true);
		// gm.setLocationSource(source);
		gm.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

			@Override
			public void onMapClick(LatLng arg0) {
				setMarker(arg0);
			}
		});

		Location current = loMan.getLastLocation();
		if (current == null) {
			Log.e("Location", "current location is null!");
			userPos = new LatLng(48.1499, 11.593801);
			CameraUpdate cup = CameraUpdateFactory
					.newCameraPosition(new CameraPosition(userPos, 15, 0, 0));
			gm.animateCamera(cup);
			// TODO handle that there is no current location

		} else {
			Log.i("UserCoordinates", "lat:" + current.getLatitude() + " lon:"
					+ current.getLongitude());
			userPos = new LatLng(current.getLatitude(), current.getLongitude());

			Log.i("location", "got last recent position");

			// zoom to last known location
			CameraUpdate cup = CameraUpdateFactory
					.newCameraPosition(new CameraPosition(userPos, 15, 0, 0));
			gm.animateCamera(cup);
			// }
		}

	}

	private void setMarker(LatLng toPosition) {
		if (selectedMark != null)
			selectedMark.remove();
		selectedMark = gm.addMarker(new MarkerOptions().position(toPosition)
				.icon(BitmapDescriptorFactory
						.fromResource((R.drawable.flag_small))));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.g, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		int id = item.getItemId();
		if (id == R.id.action_settings) {

			Intent howto = new Intent(this, Activity_HowTo.class);
			startActivity(howto);
		}

		return true;
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_g, container,
					false);
			return rootView;
		}
	}

	public void useCurrentLocation(View v) {
		
		final ImageButton b = (ImageButton) findViewById(R.id.ButtonAktGPS);
		b.setBackgroundResource(R.drawable.button_aktpos_dark);
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				b.setBackgroundResource(R.drawable.button_aktpos);
				setMarker(userPos);
			}
		}, 200);

		
	}

	public void finishTask(View v) {
		
		
		final ImageButton b = (ImageButton) findViewById(R.id.Button_SpeichernGPS);
		b.setBackgroundResource(R.drawable.weiter_dark);
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {

				b.setBackgroundResource(R.drawable.weiter);
				
				if (selectedMark == null) {
					
					Toast toast = Toast.makeText(Activity_GPS.this, "Du musst eine Position setzen!", Toast.LENGTH_SHORT);
					toast.show();
					
				} else {
					tempTaskList.get(0)
							.setLatitude(selectedMark.getPosition().latitude);
					tempTaskList.get(0).setLongitude(
							selectedMark.getPosition().longitude);

					Log.i("gps", GSonUtility.serializeTaskList(tempTaskList));

					Intent intent = new Intent(Activity_GPS.this, Activity_CreateHunt.class);
					intent.putExtra("taskInfo",
							GSonUtility.serializeTaskList(tempTaskList));
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
				}

			
		}, 100);

	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i("onStart", "connecting locationclient");
		loMan.connect();
	}

	@Override
	protected void onStop() {
		super.onStop();
		loMan.disconnect();
	}

	@Override
	protected void onResume() {
		super.onResume();

		// setUpMap();
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		//
		Log.e("locationClient", "connect failed: " + arg0.toString());
	}

	@Override
	public void onConnected(Bundle arg0) {
		// Toast.makeText(this, "LocationClient Connected",
		// Toast.LENGTH_SHORT).show();
		Log.i("locationClient", "connected");
		setUpMap();
	}

	@Override
	public void onDisconnected() {
		Toast.makeText(this, "LocatinClient Disconnected", Toast.LENGTH_SHORT)
				.show();
	}

}
